<!-- src/views/Logs.vue -->
<template>
  <div>
    <el-container>
      <el-header>
        <div class="header-content">
          <h2>日志管理</h2>
          <div>
            <el-button type="primary" @click="handleBack">
              <i class="bi bi-arrow-left"></i> 返回
            </el-button>
          </div>
        </div>
      </el-header>
      <el-main>
        <el-card shadow="hover">
          <!-- 加载指示器 -->
          <el-spin :loading="loading" tip="加载中...">
            <el-table v-if="logs.length > 0" :data="logs" style="width: 100%" stripe>
              <el-table-column prop="id" label="ID" width="50"></el-table-column>
              <el-table-column prop="action" label="操作"></el-table-column>
              <el-table-column prop="username" label="用户"></el-table-column>
              <el-table-column prop="created_at" label="时间"></el-table-column>
            </el-table>
            <!-- 无数据提示 -->
            <div v-else class="no-data">
              <el-empty description="暂无数据"></el-empty>
            </div>
          </el-spin>

          <!-- 分页组件 -->
          <div class="pagination-container" v-if="total > 0">
            <el-pagination
              background
              layout="prev, pager, next, jumper"
              :current-page="currentPage"
              :page-size="pageSize"
              :total="total"
              @current-change="handlePageChange"
            >
            </el-pagination>
          </div>
        </el-card>
      </el-main>
    </el-container>
  </div>
</template>

<script>
import axios from 'axios';
import { ref, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import { useRouter } from 'vue-router';

export default {
  name: 'Logs',
  setup() {
    const router = useRouter();
    const logs = ref([]);
    const loading = ref(false);
    const currentPage = ref(1);
    const pageSize = ref(10); 
    const total = ref(0);

    /**
     * 获取日志列表（服务端分页）
     */
    const fetchLogs = () => {
      loading.value = true;
      axios
        .get(`/api/logs?page=${currentPage.value}&limit=${pageSize.value}`)
        .then((response) => {
          if (response.data.logs && typeof response.data.total === 'number') {
            // 后端返回 { logs: [...], total: number }
            logs.value = response.data.logs.map(log => ({
              id: log.id,
              action: log.action,
              username: log.username,
              created_at: formatDate(log.created_at),
            }));
            total.value = response.data.total;
            loading.value = false;
          } else {
            ElMessage.error('获取日志列表失败，响应格式不正确');
            loading.value = false;
          }
        })
        .catch((error) => {
          console.error('获取日志列表失败:', error);
          ElMessage.error('获取日志列表失败');
          loading.value = false;
        });
    };

    /**
     * 格式化日期
     */
    const formatDate = (dateStr) => {
      if (!dateStr) return '';
      const date = new Date(dateStr);
      return date.toLocaleString();
    };

    /**
     * 点击“返回”按钮，回到仪表盘
     */
    const handleBack = () => {
      router.push('/dashboard');
    };

    /**
     * 分页切换
     */
    const handlePageChange = (page) => {
      currentPage.value = page;
      fetchLogs(); // 切换页码后重新请求后端
    };

    onMounted(() => {
      fetchLogs();
    });

    return {
      logs,
      loading,
      handleBack,
      currentPage,
      pageSize,
      total,
      handlePageChange,
    };
  },
};
</script>

<style scoped>
.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 60px;
  padding: 0 20px;
}

.el-header {
  background-color: #409eff;
  color: white;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.no-data {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 200px;
}
</style>
